<?php
    
define('APIURL','http://kpcompass.com/v3/');
define('BINDING_PATH',dirname(realpath(__FILE__)));

	
require_once(BINDING_PATH.'/kp_http.php');

class KP_AuthToken
{	
	public $devKey;
	public $url;
	public $publisher;
	
	private $http;
	
	/**
	 * Instance variables set after successful authentication 
	 */
	public $id;
	public $data;
	public $token;
	
	function __construct($devKey,$userName=NULL,$pw=NULL,$publisher='kp',$url=APIURL){
		$this->devKey = $devKey;
		$this->url = $url;
		$this->http = new KP_Http($devKey);
		$this->publisher = $publisher;
		
		if(isset($userName) && isset($pw)){
			$this->login($userName,$pw);
		}
	}
	
	public function setToken($id,$token){
		$this->id = $id;
		$this->token = $token;
	}
	
	/*
	public function authHashKey($hash){
		$data = new stdClass;
		$data->hash = $hash;
				
		$result = $this->http->post($this->url.'auth/login/',$data);
		echo 'input('.json_encode($data).')';
		echo 'raw('.json_encode($result).')';
		$this->handleResult($result);
	}	
	//*/
	
	public function login($userName,$pw){
		$data = new stdClass;
		$data->user = $userName;
		$data->pw = $pw;
		
		$result = $this->http->post($this->url.'auth/login/',$data);
		
		$this->handleResult($result);	
		
	}
	
	public function create($name,$email,$pw){
		$data = new stdClass;
		$data->name = $name;
		$data->pw = $pw;
		$data->email = $email;
		$date->publisher = $this->publisher;
		
		$result = $this->http->post($this->url.'auth/create/',$data);
		
		$this->handleResult($result);
	}
	
	private function handleResult($result){
		if($result->authenticated){
			$this->data = $result->data; 
			$this->id = $this->data->id;
			$this->hashKey = $this->data->auth;					
			$this->token = $result->cookie;				
		}
	}
}


class KP_Connection
{
	public $auth;
	public $url;
	public $devKey;
	
	private $http;
	
	function __construct($authToken){
		$this->auth = $authToken;		
		$this->url = $this->auth->url;
		$this->devKey = $this->auth->devKey;		
		$this->http = new KP_Http($this->devKey,$this->auth->token);
	}
	
	public function getCourses(){		
		return $this->http->get($this->url.'func/ple/courses/');			
	}

	public function getMessages($id){
		return $this->http->get($this->url.'func/queue/list/?id='.$id);
	}
	
	public function getOU($id){
		return $this->getDoc('ou',$id);
	}
	
	public function getUP($id){
		return $this->getDoc('unitplan',$id);
	}
	
	public function getPage($id){
		return $this->getDoc('page',$id);
	}
	
	/**
	 * internal function do not directly access.
	 */
	private function getDoc($type,$id){
		return $this->http->get($this->url.'docs/'.$type.'/'.$id.'/');
	}
	
	public function getAssessment($id){
		return $this->http->get($this->url.'func/test/assessment/?id='.$id);
	}
	
	public function getPractice($id){
		return $this->http->get($this->url.'func/test/remediate/?id='.$id);
	}
	
	public function gradeTest($id,$answers,$type="remediated"){
		$data = new stdClass;
		$data->id = $id;
		$data->type = $type;
		$data->questions = $answers;
		
		//echo json_encode($data);
		return $this->http->post($this->url.'func/test/grade/',$data);
	}

	/**
	 * $code is the class code associated with the class you want to add.
	 * returns the new token for the user.
	 */
	public function addProduct($code){
		return $this->handleProductChange($this->url.'func/ple/addClass/', $code);
	}
	
	/**
	 * $code is the class code associated with the class you want to remove.
	 * returns the new token for the user.
	 */
	public function removeProduct($code){
		return $this->handleProductChange($this->url.'func/ple/deleteClass/', $code);
	}
	
	/**
	 * internal function do not directly access.
	 */
	private function handleProductChange($url,$code){
		$data = new stdClass;
		$data->code = $code;
		
		$result = $this->http->post($url,$data);
		$token = $result->verified?$result->cookie:NULL;
		$this->auth->token = $token;
		return $token;
	}

}

class KP_HELPER
{
	public $rewrite;
	
	function __construct($useRewriteRules=FALSE){
		$this->rewrite = !$useRewriteRules;
	}
	
	public function urnToId($urn){
		$id = $urn;
		if(strpos($urn,'urn+kpedu+') === 0){
			$parts = explode('+', $urn);
			$id = $parts[count($parts)-1];			
		}
		return $id;
	}
	
	public function aptitudeToLevel($aptitude){
		$level = '';		
		if($aptitude == 0){
			$level = 'untested';
		}else if($aptitude <= .5){
			$level = "novice";
		}else if($aptitude <= .9){
			$level = "apprentice";
		}else{
			$level = "scholar";
		}
		return $level;
	}
	
	public function processHtml($html,$base){
		$html = $this->removeCrap($html);
		$html = $this->overwritePageLinks($html, $base);
		$html = $this->replaceCDNRedirects($html);
		return $html;
	}
	
	protected function removeCrap($html){
		$html = preg_replace('/<div class="magnify".*?div>/s','',$html);		
		return $html;
	}
	
	protected function overwritePageLinks($html,$base){
		$html = preg_replace('/Doc\/Page\//',$base.'?type=page&id=',$html);
		return $html;
	}
	
	/**
	 * We use internally rewrite rules to replace
	 * RewriteRule ^images/(.*?)$  http://c1811622.r22.cf0.rackcdn.com/$1 [R=301,L]
	 * RewriteRule ^media/(.*?)$  http://c1802442.r42.cf0.rackcdn.com/$1 [R=301,L] 
	 * RewriteRule ^movies/(.*?)$  http://c1802442.r42.cf0.rackcdn.com/$1 [R=301,L]
	 * RewriteRule ^resources/(.*?)$  http://c3151522.r22.cf0.rackcdn.com/$1 [R=301,L] 
	 * RewriteRule ^usercreated/(.*?)$  http://c3364788.r88.cf0.rackcdn.com/$1 [R=301,L]
	 * 
	 * If $userRequireRules in the constructor is set to False we will regex replace instead of assuming rules.
	 */
	protected function replaceCDNRedirects($html){
		if($this->rewrite){
			$html = preg_replace('/\/images\//','http://c1811622.r22.cf0.rackcdn.com/',$html);
			$html = preg_replace('/\/media\//','http://c1802442.r42.cf0.rackcdn.com/',$html);
			$html = preg_replace('/\/movies\//','http://c1802442.r42.cf0.rackcdn.com/',$html);
			$html = preg_replace('/\/resources\//','http://c3151522.r22.cf0.rackcdn.com/',$html);
			$html = preg_replace('/\/usercreated\//','http://c3364788.r88.cf0.rackcdn.com/',$html);
		}
		return $html;
	}
}
?>